{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quantization-aware training with range learning\n",
    "\n",
    "This notebook contains a working example of AIMET Quantization-aware training (QAT). \n",
    "QAT is an AIMET feature that adds quantization simulation operations (also called fake quantization ops) to a trained ML model. \n",
    "A standard training pipeline is then used to train or fine-tune the model. \n",
    "The resulting model should show improved accuracy on quantized ML accelerators.\n",
    "\n",
    "AIMET supports two different types of QAT:\n",
    "\n",
    "**QAT without range learning (or just \"QAT\")**: Quantization parameters like per-tensor scale and offsets for activations are computed once. During fine-tuning, quantization parameters are held constant as the model weights are updated to minimize the effects of quantization in the forward pass.\n",
    "\n",
    "**QAT with range learning**: The same quantization parameters are computed initially. Then both the quantization parameters and the model weights are jointly updated during fine-tuning to minimize the effects of quantization in the forward pass.\n",
    "\n",
    "This example is for QAT *with* range learning. An example of QAT without range learning is [here](./qat.ipynb).\n",
    "\n",
    "## Overall flow\n",
    "\n",
    "The example follows these high-level steps:\n",
    "\n",
    "1. Instantiate the example evaluation and training pipeline\n",
    "2. Load the FP32 model and evaluate the model to find the baseline FP32 accuracy\n",
    "3. Create a quantization simulation model (with fake quantization ops) and evaluate the quantized simuation model\n",
    "4. Fine-tune the quantization simulation model and evaluate the fine-tuned simulation model, which should reflect the accuracy on a quantized ML platform.\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "\n",
    "Note\n",
    "\n",
    "This notebook does not show state-of-the-art results. For example, it uses a relatively quantization-friendly model (Resnet18). Also, some optimization parameters like number of fine-tuning epochs are chosen to improve execution speed in the notebook.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Dataset\n",
    "\n",
    "This example does image classification on the ImageNet dataset. If you already have a version of the data set, use that. Otherwise download the data set, for example from https://image-net.org/challenges/LSVRC/2012/index .\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "\n",
    "Note\n",
    "\n",
    "The dataloader provided in this example relies on these features of the ImageNet data set:\n",
    "\n",
    "- Subfolders `train` for the training samples and `val` for the validation samples. See the [pytorch dataset description](https://pytorch.org/vision/0.8/_modules/torchvision/datasets/imagenet.html) for more details.\n",
    "- One subdirectory per class, and one file per image sample.\n",
    "\n",
    "</div>\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "\n",
    "Note\n",
    "\n",
    "To speed up the execution of this notebook, you can use a reduced subset of the ImageNet dataset. For example: The entire ILSVRC2012 dataset has 1000 classes, 1000 training samples per class and 50 validation samples per class. However, for the purpose of running this notebook, you can reduce the dataset to, say, two samples per class.\n",
    "\n",
    "</div>\n",
    "\n",
    "Edit the cell below to specify the directory where the downloaded ImageNet dataset is saved."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": true
    }
   },
   "outputs": [],
   "source": [
    "DATASET_DIR = '/path/to/dataset/'         # Replace this path with a real directory"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 1. Instantiate the example training and validation pipeline\n",
    "\n",
    "**Use the following training and validation loop for the image classification task.**\n",
    "\n",
    "Things to note:\n",
    "\n",
    "- AIMET does not put limitations on how the training and validation pipeline is written. AIMET modifies the user's model to create a QuantizationSim model, which is still a PyTorch model. The QuantizationSim model can be used in place of the original model when doing inference or training.\n",
    "- AIMET doesn not put limitations on the interface of the `evaluate()` or `train()` methods. You should be able to use your existing evaluate and train routines as-is.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": true
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import torch\n",
    "from Examples.common import image_net_config\n",
    "from Examples.torch.utils.image_net_evaluator import ImageNetEvaluator\n",
    "from Examples.torch.utils.image_net_trainer import ImageNetTrainer\n",
    "from Examples.torch.utils.image_net_data_loader import ImageNetDataLoader\n",
    "\n",
    "class ImageNetDataPipeline:\n",
    "\n",
    "    @staticmethod\n",
    "    def get_val_dataloader() -> torch.utils.data.DataLoader:\n",
    "        \"\"\"\n",
    "        Instantiates a validation dataloader for ImageNet dataset and returns it\n",
    "        \"\"\"\n",
    "        data_loader = ImageNetDataLoader(DATASET_DIR,\n",
    "                                         image_size=image_net_config.dataset['image_size'],\n",
    "                                         batch_size=image_net_config.evaluation['batch_size'],\n",
    "                                         is_training=False,\n",
    "                                         num_workers=image_net_config.evaluation['num_workers']).data_loader\n",
    "        return data_loader\n",
    "\n",
    "    @staticmethod\n",
    "    def evaluate(model: torch.nn.Module, use_cuda: bool) -> float:\n",
    "        \"\"\"\n",
    "        Given a torch model, evaluates its Top-1 accuracy on the dataset\n",
    "        :param model: the model to evaluate\n",
    "        :param use_cuda: whether or not the GPU should be used.\n",
    "        \"\"\"\n",
    "        evaluator = ImageNetEvaluator(DATASET_DIR, image_size=image_net_config.dataset['image_size'],\n",
    "                                      batch_size=image_net_config.evaluation['batch_size'],\n",
    "                                      num_workers=image_net_config.evaluation['num_workers'])\n",
    "\n",
    "        return evaluator.evaluate(model, iterations=None, use_cuda=use_cuda)\n",
    "\n",
    "    @staticmethod\n",
    "    def finetune(model: torch.nn.Module, epochs, learning_rate, learning_rate_schedule, use_cuda):\n",
    "        \"\"\"\n",
    "        Given a torch model, finetunes the model to improve its accuracy\n",
    "        :param model: the model to finetune\n",
    "        :param epochs: The number of epochs used during the finetuning step.\n",
    "        :param learning_rate: The learning rate used during the finetuning step.\n",
    "        :param learning_rate_schedule: The learning rate schedule used during the finetuning step.\n",
    "        :param use_cuda: whether or not the GPU should be used.\n",
    "        \"\"\"\n",
    "        trainer = ImageNetTrainer(DATASET_DIR, image_size=image_net_config.dataset['image_size'],\n",
    "                                  batch_size=image_net_config.train['batch_size'],\n",
    "                                  num_workers=image_net_config.train['num_workers'])\n",
    "\n",
    "        trainer.train(model, max_epochs=epochs, learning_rate=learning_rate,\n",
    "                      learning_rate_schedule=learning_rate_schedule, use_cuda=use_cuda)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 2. Load the model and evaluate to get a baseline FP32 accuracy score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**2.1 Load a pretrained resnet18 model from torchvision.** \n",
    "\n",
    "You can load any pretrained PyTorch model instead."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torchvision.models import resnet18\n",
    "\n",
    "model = resnet18(pretrained=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "AIMET quantization simulation requires the model definition to follow certain guidelines. For example, functionals defined in the forward pass should be changed to the equivalent **torch.nn.Module**.\n",
    "The [AIMET user guide](https://quic.github.io/aimet-pages/releases/latest/user_guide/index.html) lists all these guidelines.\n",
    "\n",
    "**2.2 Use the following ModelPreparer API call to automate the model definition changes required to comply with the AIMET guidelines.** \n",
    "\n",
    "The call uses the graph transformation feature available in PyTorch 1.9+."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from aimet_torch.model_preparer import prepare_model\n",
    "\n",
    "model = prepare_model(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**2.3 Decide whether to place the model on a CPU or CUDA device.** \n",
    "\n",
    "This example uses CUDA if it is available. You can change this logic and force a device placement if needed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "use_cuda = False\n",
    "if torch.cuda.is_available():\n",
    "    use_cuda = True\n",
    "    model.to(torch.device('cuda'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**2.4 Compute the floating point 32-bit (FP32) accuracy of this model using the evaluate() routine.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "accuracy = ImageNetDataPipeline.evaluate(model, use_cuda)\n",
    "print(accuracy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 3. Create a quantization simulation model and determine quantized accuracy\n",
    "\n",
    "### Fold Batch Normalization layers\n",
    "\n",
    "Before calculating the simulated quantized accuracy using QuantizationSimModel, fold the BatchNormalization (BN) layers into adjacent Convolutional layers. The BN layers that cannot be folded are left as they are.\n",
    "\n",
    "BN folding improves inference performance on quantized runtimes but can degrade accuracy on these platforms. This step simulates this on-target drop in accuracy. \n",
    "\n",
    "**3.1 Use the following code to call AIMET to fold the BN layers in-place on the given model.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from aimet_torch.v1.batch_norm_fold import fold_all_batch_norms\n",
    "\n",
    "_ = fold_all_batch_norms(model, input_shapes=(1, 3, 224, 224))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create the Quantization Sim Model\n",
    "\n",
    "**3.2 Use AIMET to create a QuantizationSimModel.**\n",
    "\n",
    " In this step, AIMET inserts fake quantization ops in the model graph and configures them.\n",
    "\n",
    "Key parameters:\n",
    "\n",
    "- Setting **quant_scheme** to \"training_range_learning_with_tf_init\" enables range learning. AIMET sets scale and offset to be trainable so that they are updated during fine-tuning. \n",
    "- Setting **default_output_bw** to 8 performs all activation quantizations in the model using integer 8-bit precision\n",
    "- Setting **default_param_bw** to 8 performs all parameter quantizations in the model using integer 8-bit precision\n",
    "\n",
    "See [QuantizationSimModel in the AIMET API documentation](https://quic.github.io/aimet-pages/AimetDocs/api_docs/torch_quantsim.html#aimet_torch.quantsim.QuantizationSimModel.compute_encodings) for a full explanation of the parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from aimet_common.defs import QuantScheme\n",
    "from aimet_torch.v1.quantsim import QuantizationSimModel\n",
    "\n",
    "dummy_input = torch.rand(1, 3, 224, 224)    # Shape for each ImageNet sample is (3 channels) x (224 height) x (224 width)\n",
    "if use_cuda:\n",
    "    dummy_input = dummy_input.cuda()\n",
    "\n",
    "sim = QuantizationSimModel(model=model,\n",
    "                           quant_scheme=QuantScheme.training_range_learning_with_tf_init\\,\n",
    "                           dummy_input=dummy_input,\n",
    "                           default_output_bw=8,\n",
    "                           default_param_bw=8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "**3.3 Print the model to verify the modifications AIMET has made. **\n",
    "\n",
    "Note that AIMET has added quantization wrapper layers. \n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "\n",
    "Note\n",
    "\n",
    "Use sim.model to access the modified PyTorch model. By default, AIMET creates a copy of the original model prior to modifying it. There is a parameter to override this behavior.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(sim.model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "Note also that AIMET has configured the added fake quantization nodes, which AIMET refers to as \"quantizers\". \n",
    "\n",
    "**3.4 Print the sim object to see the quantizers.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(sim)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "AIMET has added quantizer nodes to the model graph, but before the sim model can be used for inference or training, scale and offset quantization parameters must be calculated for each quantizer node by passing unlabeled data samples through the model to collect range statistics. This process is sometimes referred to as calibration. AIMET refers to it as \"computing encodings\".\n",
    "\n",
    "**3.5 Create a routine to pass unlabeled data samples through the model.** \n",
    "\n",
    "The following code is one way to write a routine that passes unlabeled samples through the model to compute encodings. It uses the existing train or validation data loader to extract samples and pass them to the model. Since there is no need to compute loss metrics, it ignores the model output.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pass_calibration_data(sim_model, use_cuda):\n",
    "    data_loader = ImageNetDataPipeline.get_val_dataloader()\n",
    "    batch_size = data_loader.batch_size\n",
    "\n",
    "    if use_cuda:\n",
    "        device = torch.device('cuda')\n",
    "    else:\n",
    "        device = torch.device('cpu')\n",
    "\n",
    "    sim_model.eval()\n",
    "    samples = 1000\n",
    "\n",
    "    batch_cntr = 0\n",
    "    with torch.no_grad():\n",
    "        for input_data, target_data in data_loader:\n",
    "\n",
    "            inputs_batch = input_data.to(device)\n",
    "            sim_model(inputs_batch)\n",
    "\n",
    "            batch_cntr += 1\n",
    "            if (batch_cntr * batch_size) > samples:\n",
    "                break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A few notes regarding the data samples:\n",
    "\n",
    "- A very small percentage of the data samples are needed. For example, the training dataset for ImageNet has 1M samples; 500 or 1000 suffice to compute encodings.\n",
    "- The samples should be reasonably well distributed. While it's not necessary to cover all classes, avoid extreme scenarios like using only dark or only light samples. That is, using only pictures captured at night, say, could skew the results.\n",
    "\n",
    "---\n",
    "\n",
    "**3.6 Call AIMET to use the routine to pass data through the model and compute the quantization encodings.** \n",
    "\n",
    "Encodings here refer to scale and offset quantization parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sim.compute_encodings(forward_pass_callback=pass_calibration_data,\n",
    "                      forward_pass_callback_args=use_cuda)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "The QuantizationSim model is now ready to be used for inference or training. \n",
    "\n",
    "**3.7 Pass the model to the same evaluation routine as before to calculate a simulated quantized accuracy score for INT8 quantization for comparison with the FP32 score.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "accuracy = ImageNetDataPipeline.evaluate(sim.model, use_cuda)\n",
    "print(accuracy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 4. Perform QAT\n",
    "\n",
    "**4.1 To perform quantization aware training (QAT), train the model for a few more epochs (typically 15-20).** \n",
    "\n",
    "As with any training job, hyper-parameters need to be searched for optimal results. Good starting points are to use a learning rate on the same order as the ending learning rate when training the original model, and to drop the learning rate by a factor of 10 every 5 epochs or so.\n",
    "\n",
    "This example trains for only 1 epoch, but you can experiment with the parameters however you like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ImageNetDataPipeline.finetune(sim.model, epochs=1, learning_rate=5e-7, learning_rate_schedule=[5, 10], use_cuda=use_cuda)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**4.2 After QAT finishes, run quantization simulation inference against the validation dataset to see improvements in accuracy.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "finetuned_accuracy = ImageNetDataPipeline.evaluate(sim.model, use_cuda)\n",
    "print(finetuned_accuracy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "Of course, there might be little gain in accuracy after only one epoch of training. Experiment with the hyper-parameters to get better results.\n",
    "\n",
    "## Next steps\n",
    "\n",
    "The next step is to export this model for installation on the target.\n",
    "\n",
    "**Export the model and encodings.**\n",
    "\n",
    "- Export the model with the updated weights but without the fake quant ops. \n",
    "- Export the encodings (scale and offset quantization parameters). AIMET QuantizationSimModel provides an export API for this purpose.\n",
    "\n",
    "The following code performs these exports."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.makedirs('./output/', exist_ok=True)\n",
    "dummy_input = dummy_input.cpu()\n",
    "sim.export(path='./output/', filename_prefix='resnet18_after_qat', dummy_input=dummy_input)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## For more information\n",
    "\n",
    "See the [AIMET API docs](https://quic.github.io/aimet-pages/AimetDocs/api_docs/index.html) for details about the AIMET APIs and optional parameters.\n",
    "\n",
    "See the [other example notebooks](https://github.com/quic/aimet/tree/develop/Examples/torch/quantization) to learn how to use QAT with other AIMET post-training quantization techniques."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
